package com.mxx.qh.activity;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;
import com.mxx.qh.R;
import com.mxx.qh.SPUtils;
import com.mxx.qh.WXAuthorizeBroadCast;
import com.mxx.qh.WxAuthorizeInfoListener;
import com.mxx.qh.config.ConstantsConfig;
import com.mxx.qh.dialog.IdentificationUnknownDialog;
import com.mxx.qh.dialog.TokenEmptyDialog;
import com.mxx.qh.network.RequestEnum;
import com.mxx.qh.network.RetrofitHelper;
import com.mxx.qh.network.StringObserver;
import com.mxx.qh.response.AuthorizeInfo;
import com.mxx.qh.response.BaseResponse;
import com.mxx.qh.response.WXUserInfo;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

public class LoginActivity extends BaseActivity implements TokenEmptyDialog.WxAuthorizeListener
        , WxAuthorizeInfoListener, IdentificationUnknownDialog.OpenWxListener {
    private int type;
    private WXAuthorizeBroadCast wxAuthorizeBroadCast;
    private boolean isFirst;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_login;
    }

    @Override
    protected void setStatusBar() {
        ImmersionBar
                .with(this)
                .fitsSystemWindows(false)
                .statusBarColor(android.R.color.white)
                .statusBarDarkFont(true)
                .init();
    }

    @Override
    protected void initView() {
        Log.i("LoginActivity", "initView");
    }

    @Override
    protected void initData() {
        Log.i("LoginActivity", "initData");
        type = getType();
        isFirst = true;
    }

    private int getType() {
        Intent mIntent = getIntent();
        if (mIntent == null) {
            return 0;
        }
        Bundle mBundle = mIntent.getExtras();
        if (mBundle == null) {
            return 0;
        }

        return (int) mBundle.getSerializable(ConstantsConfig.TYPE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isFirst) {
            isFirst = false;
            showDialogByType(type);
        }
    }

    private void showDialogByType(int type) {
        if (type == 1) {
            showAuthorizeLoginDialog();
        }

        if (type == 2) {
            showFriendlyHintDialog();
        }
    }

    private void showAuthorizeLoginDialog() {
        TokenEmptyDialog tokenEmptyDialog = new TokenEmptyDialog();
        tokenEmptyDialog.setWxAuthorizeListener(this);
        tokenEmptyDialog.show(getSupportFragmentManager(), "TokenEmptyDialog");
    }

    @Override
    public void wxAuthorize() {
        initBroadCast();
        WXLogin();
    }

    private void initBroadCast() {
        //注册广播接收器
        wxAuthorizeBroadCast = new WXAuthorizeBroadCast();
        wxAuthorizeBroadCast.setWxAuthorizeInfoListener(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WXAuthorizeBroadCast.WX_AUTHORIZE_ACTION);
        registerReceiver(wxAuthorizeBroadCast, intentFilter);
    }

    private void WXLogin() {
        IWXAPI api = WXAPIFactory.createWXAPI(this, ConstantsConfig.WX_APP_ID, false);
        // 判断是否安装了微信客户端
        if (!api.isWXAppInstalled()) {
            Toast.makeText(this, "您还未安装微信客户端", Toast.LENGTH_SHORT).show();
            return;
        }
        // 发送授权登录信息，来获取code
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "qianhe";
        api.sendReq(req);
    }

    @Override
    public void getAuthorizeInfoSuccess(String state, String code) {
        unregisterReceiver(wxAuthorizeBroadCast);
        sendGetTokenRequest(state, code);
    }

    private void sendGetTokenRequest(String state, String code) {
        new RetrofitHelper
                .Builder()
                .baseUrl("http://qianhe.jiaoliuton.com/api/")
                .appendUrl("wechat/user?code=" + code + "&state=" + state + "&type=" + "android")
                .build()
                .observable(RequestEnum.METHOD_GET_NO_PARAMS)
                .subscribe(new StringObserver() {
                    @Override
                    protected void onSuccess(String json) {
                        try {
                            String token = getToken(json);
                            saveToken(token);
                            sendGetWxUserInfo(token);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    protected void onFailed(Integer code, String msg) {
                        String message = "";
                        if (code != null) {
                            message = message + code + "\n";
                        }
                        message = message + msg;
                        Toast.makeText(LoginActivity.this, message, Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private String getToken(String json) {
        String token;
        Gson gson = new Gson().newBuilder().create();
        BaseResponse<AuthorizeInfo> response = gson.fromJson(json, new TypeToken<BaseResponse<AuthorizeInfo>>() {
        }.getType());
        AuthorizeInfo authorizeInfo = gson.fromJson(gson.toJson(response.data), new TypeToken<AuthorizeInfo>() {
        }.getType());
        token = authorizeInfo.token;
        return token;
    }

    private void saveToken(String token) {
        SPUtils.put(LoginActivity.this, ConstantsConfig.TOKEN, token);
    }

    private void sendGetWxUserInfo(String token) {
        if (token == null || token.isEmpty()) {
            Toast.makeText(LoginActivity.this, "用户登录缺少必要的参数", Toast.LENGTH_SHORT).show();
            return;
        }
        new RetrofitHelper
                .Builder()
                .baseUrl("http://qianhe.jiaoliuton.com/api/")
                .appendUrl("user/info?token=" + token)
                .build()
                .observable(RequestEnum.METHOD_GET_NO_PARAMS)
                .subscribe(new StringObserver() {
                    @Override
                    protected void onSuccess(String json) {
                        WXUserInfo info = getWxUserInfo(json);
                        int is_sex_unknown = getIsSex(info);
                        saveWXUserInfo(is_sex_unknown);
                        showDialogOrSkipToMain(is_sex_unknown);
                    }

                    @Override
                    protected void onFailed(Integer code, String msg) {
                        String message = "";
                        if (code != null) {
                            message = message + code + "\n";
                        }
                        message = message + msg;
                        Toast.makeText(LoginActivity.this, message, Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private WXUserInfo getWxUserInfo(String json) {
        Gson gson = new Gson().newBuilder().create();
        BaseResponse<WXUserInfo> response = gson.fromJson(json, new TypeToken<BaseResponse<WXUserInfo>>() {
        }.getType());
        return gson.fromJson(gson.toJson(response.data), new TypeToken<WXUserInfo>() {
        }.getType());
    }

    private int getIsSex(WXUserInfo info) {
        int isSex = 2;
        if (info != null) {
            isSex = info.is_sex_unknown;
        }

        return isSex;
    }

    private void saveWXUserInfo(int is_sex_unknown) {
        SPUtils.put(this, ConstantsConfig.IDENTIFICATION, is_sex_unknown);
    }

    private void showDialogOrSkipToMain(int is_sex_unknown) {
        if (is_sex_unknown == 2) {
            showDialogByType(2);
        } else {
            skipToMain();
        }
    }

    private void skipToMain() {
        String token = (String) SPUtils.get(this, ConstantsConfig.TOKEN, "");
        Bundle mBundle = new Bundle();
        String url = "http://qianhe.jiaoliuton.com/#/authorize1/" + token + "&app=app";
        mBundle.putSerializable(ConstantsConfig.VALUE, url);
        Intent mIntent = new Intent(this, MainActivity.class);
        mIntent.putExtras(mBundle);
        startActivity(mIntent);
        finish();
        //取消界面跳转时的动画，使启动页的logo图片与注册、登录主页的logo图片完美衔接
        overridePendingTransition(0, 0);
    }

    @Override
    public void getAuthorizeInfoFail(String errInfo) {
        unregisterReceiver(wxAuthorizeBroadCast);
    }


    private void showFriendlyHintDialog() {
        IdentificationUnknownDialog identificationUnknownDialog = new IdentificationUnknownDialog();
        identificationUnknownDialog.setOpenWxListener(this);
        identificationUnknownDialog.show(getSupportFragmentManager(), "IdentificationUnknownDialog");
    }


    @Override
    public void openWxToPersonalInfo() {
        Log.i("TAG", "");
    }
}